import React, { useRef, useEffect, useState, FormEvent } from 'react';
import { Button, message, Row, Col, Input } from 'antd';
import ProForm, {
    ProFormSelect,
    ProFormText,
    ProFormDatePicker,
    ProFormUploadButton,
} from '@ant-design/pro-form';
import styles from './index.scss';
import _ from 'lodash';
import type { ProFormInstance } from '@ant-design/pro-form';
import {
    fetchBookTypeList,
    addBook,
    batchAddBook,
    getScannerInfo,
    getScannerInfoForIsbn,
    getScannerInfoForRfid,
} from '@/service/enrollBook';
import { BookType, EnrollBookState } from './interface';
import { UploadProps } from 'antd/lib/upload';
import useRerender from '@/hooks/useRerender';
import { uploadFile } from '@/service/personnelEntry';
import { history } from 'umi';
import { scanEvent } from '../../utils/qrCode';
type NamePath = string | number | (string | number)[];
export default function Edit(props: any) {
    const [form] = ProForm.useForm();
    const myIsbnInput = useRef(null);
    const myRfidInput = useRef(null);
    const rerender = useRerender();
    const [bookTypeList, setbookTypeList] = useState<BookType[]>();

    const dataSourceRequest = async () => {
        const response = await fetchBookTypeList();
        if (response?.data) {
            setbookTypeList(response.data || []);
        }
    };
    function transformToFormData(values: any[]): any[] {
        return values.map((item: any) => {
            return {
                ...item,
                ...(item.img_url
                    ? { img_url: [{ response: item.img_url }] }
                    : {}),
            };
        });
    }
    const getScannerInfoForRfidFn = async (item: string) => {
        let response = await getScannerInfoForRfid({
            test: '',
        });
        if (response?.data) {
            form.setFields(transFormData(item, response.data));
        }
    };

    const transFormData = (index: string, response: any) => {
        const arr = [];
        for (let i in response) {
            if (i === 'img_url') {
                arr.push({
                    name: [index, i],
                    value: [{ response: response[i] }],
                });
            } else {
                arr.push({
                    name: [index, i],
                    value: response[i],
                });
            }
        }
        return arr;
    };
    const getScannerInfoForIsbnRequest = async (item: string, isbn: string) => {
        const response = await getScannerInfoForIsbn({ isbn });
        if (response?.data) {
            message.success('识别成功');
            console.log(form.getFieldsValue(true));
            form.setFields(transFormData(item, response.data));
            const myRfidInputObj: any = myRfidInput.current;
            myRfidInputObj && myRfidInputObj.focus();
            await getScannerInfoForRfidFn(item);
            // form.setFieldsValue({
            //     ...form.getFieldsValue(true),
            //     book_name:response.data.book_name,
            //     [obj.id]: transformToFormData([response.data]).reduce(
            //         (result: any, item: any, index: number) => {
            //             result[index] = item;
            //             return result;
            //         },
            //         {},
            //     )[0],
            // });
        }
    };
    const mapDebounceHandler = _.debounce(getScannerInfoForIsbnRequest, 1000); //节流
    const [list, setlist] = useState<string[]>(['0']);
    const submitAdd = async (data: EnrollBookState) => {
        const res = await addBook(data);
        if (res?.code === 200) {
            message.success('提交成功');
            history.push('/enrollBook');
        } else {
            message.warning('提交失败');
        }
    };
    const submitBatchAdd = async (data: string) => {
        const res = await batchAddBook({ bookInfo: data });
        if (res?.code === 200) {
            message.success('提交成功');
            history.push('/enrollBook');
        } else {
            message.warning('提交失败');
        }
    };
    useEffect(() => {
        setTimeout(() => {
            const myIsbnInputObj: any = myIsbnInput.current;
            myIsbnInputObj && myIsbnInputObj.focus();
        }, 1000);
        dataSourceRequest();
    }, []);
    const getOptions = () => {
        return bookTypeList?.map((item) => {
            return {
                value: item.id,
                label: item.cate_name,
            };
        });
    };
    const customRequest: UploadProps['customRequest'] = async (options) => {
        // console.log(options);
        const formdata = new FormData();
        formdata.append('field', 'book');
        formdata.append('book', options.file);
        const res = await uploadFile(formdata);
        if (res.code !== 200) {
            message.error(res.msg);
            return;
        }
        options.onSuccess?.(res.data.url);
        rerender();
    };
    const formRef = useRef<ProFormInstance>();

    const validateAndGetFormatValue = () => {
        formRef.current?.validateFieldsReturnFormatValue?.().then((values) => {
            let arr: EnrollBookState[] = [];
            console.log(values);
            Object.keys(values).map((i) => {
                let obj = values[i];
                obj.img_url = values[i]?.img_url[0]?.response;
                arr.push(obj);
            });
            if (arr.length < 1) {
                submitAdd(arr[0]);
            } else {
                submitBatchAdd(JSON.stringify(arr));
            }
        });
    };
    const scanWrapper = async (e: any) => {
        let data = await scanEvent(e, () => {
            // to do something...
        });
        console.log(data);
        if (data.flag) {
            console.log(data.code);
        }
    };
    const IsbnProFormText = (props: any) => {
        return (
            <ProForm.Item {...props}>
                <Input
                    placeholder={props.placeholder}
                    {...props.fieldProps}
                    ref={myIsbnInput}
                />
            </ProForm.Item>
        );
    };
    const RfidProFormText = (props: any) => {
        return (
            <ProForm.Item {...props}>
                <Input
                    placeholder={props.placeholder}
                    {...props.fieldProps}
                    ref={myRfidInput}
                />
            </ProForm.Item>
        );
    };
    return (
        <>
            <ProForm formRef={formRef} form={form} submitter={false}>
                {list.map((item) => {
                    return (
                        <div
                            key={item}
                            style={{
                                background: '#fff',
                                padding: '20px',
                                marginBottom: '20px',
                            }}
                        >
                            <ProForm.Group>
                                <RfidProFormText
                                    rules={[
                                        {
                                            required: true,
                                            message: '这是必填项',
                                        },
                                    ]}
                                    width="md"
                                    name={[item, 'rfid'].flat(Infinity)}
                                    label="RFID编号"
                                    placeholder="请输入RFID编号"
                                    fieldProps={{
                                        onChangeCapture: async (e: any) => {
                                            // let value = form.getFieldValue(
                                            //     [item, 'rfid'].flat(Infinity),
                                            // );
                                            // let data = await scanEvent(
                                            //     e,
                                            //     () => {
                                            //         // to do something...
                                            //     },
                                            // );
                                            // if (data.flag) {
                                            //     getScannerInfoRequest(
                                            //         e.target.value,
                                            //     );
                                            // } else {
                                            //     form.setFields([
                                            //         {
                                            //             name: [item, 'rfid'],
                                            //             value: value,
                                            //         },
                                            //     ]);
                                            // }
                                        },
                                    }}
                                />
                                <IsbnProFormText
                                    rules={[
                                        {
                                            required: true,
                                            message: '这是必填项',
                                        },
                                    ]}
                                    width="md"
                                    name={[item, 'isbn'].flat(Infinity)}
                                    label="ISBN编号"
                                    placeholder="请输入ISBN编号"
                                    fieldProps={{
                                        onChangeCapture: async (e: any) => {
                                            console.log('====更改====', e);
                                            mapDebounceHandler(
                                                item,
                                                e.target.value,
                                            );
                                            // debounce(getScannerInfoForIsbnRequest(
                                            //     item,
                                            //     e.target?.value,
                                            // ),3000);
                                        },
                                    }}
                                />
                                <ProFormText
                                    rules={[
                                        {
                                            required: true,
                                            message: '这是必填项',
                                        },
                                    ]}
                                    width="md"
                                    name={[item, 'book_name'].flat(Infinity)}
                                    label="书名"
                                    placeholder="请输入书名"
                                />
                                <ProFormText
                                    rules={[
                                        {
                                            required: true,
                                            message: '这是必填项',
                                        },
                                    ]}
                                    width="md"
                                    name={[item, 'author'].flat(Infinity)}
                                    label="作者"
                                    placeholder="请输入作者"
                                />
                            </ProForm.Group>
                            <ProForm.Group>
                                <ProFormDatePicker
                                    rules={[
                                        {
                                            required: true,
                                            message: '这是必填项',
                                        },
                                    ]}
                                    width="md"
                                    name={[item, 'publish_date'].flat(Infinity)}
                                    label="出版时间"
                                />
                                <ProFormText
                                    rules={[
                                        {
                                            required: true,
                                            message: '这是必填项',
                                        },
                                    ]}
                                    width="md"
                                    name={[item, 'publishing_house'].flat(
                                        Infinity,
                                    )}
                                    label="出版社"
                                    placeholder="请输入出版社"
                                />
                                <ProFormSelect
                                    options={getOptions()}
                                    width="sm"
                                    name={[item, 'cate_id'].flat(Infinity)}
                                    label="类别"
                                />
                            </ProForm.Group>
                            <ProFormUploadButton
                                fieldProps={{ customRequest }}
                                max={1}
                                accept="image/*"
                                title="上传图片"
                                listType="picture-card"
                                name={
                                    [item, 'img_url'].flat(
                                        Infinity,
                                    ) as NamePath & string
                                }
                                rules={[
                                    { required: true, message: '这是必填项' },
                                ]}
                                label="封面上传"
                            />
                            <div style={{ textAlign: 'right' }}>
                                <Button
                                    onClick={() => {
                                        form.resetFields([item]);
                                        rerender();
                                    }}
                                >
                                    清空
                                </Button>
                                <Button
                                    style={{ marginLeft: '10px' }}
                                    onClick={() => {
                                        if (list.length > 1) {
                                            let arr = list.filter(
                                                (i) => i !== item,
                                            );
                                            setlist(arr);
                                        }
                                    }}
                                >
                                    删除
                                </Button>
                            </div>
                        </div>
                    );
                })}
            </ProForm>
            <Row justify="space-between" className={styles.bottomButton}>
                <Col>
                    <Button
                        type="primary"
                        onClick={() => {
                            let num = list[list.length - 1] + 1;
                            setlist(list.concat([num]));
                        }}
                    >
                        新增
                    </Button>
                </Col>
                <Col>
                    <Button
                        onClick={() => {
                            history.push('/enrollBook');
                        }}
                    >
                        取消
                    </Button>
                    <Button
                        style={{
                            border: '1px solid #1890ff',
                            marginLeft: '20px',
                            color: 'rgb(24, 144, 255)',
                        }}
                        onClick={() => validateAndGetFormatValue()}
                    >
                        提交
                    </Button>
                </Col>
            </Row>
        </>
    );
}
